package com.woniu.hander;

import com.alibaba.fastjson.JSON;
import com.woniu.util.JWTUtil;
import com.woniu.util.ResData;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired(required = false)
    private RedisTemplate<String,String> redisTemplate;

    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication)
            throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");

        User userInfo = (User) authentication.getPrincipal();
        Map map = new HashMap();
        map.put("username",userInfo.getUsername());
        String jwt = JWTUtil.createJWT(map);
        //把jwt放入redis
        redisTemplate.opsForValue().set("jwt:"+userInfo.getUsername(),jwt,30, TimeUnit.MINUTES);
        System.out.println("登录成功"+jwt);
        PrintWriter writer = httpServletResponse.getWriter();

        writer.print(JSON.toJSONString(new ResData<>().ok(jwt)));
        writer.flush();
        writer.close();
    }
}
